var express = require('express');
var md5 = require('md5');
var router = express.Router();
const query = require("../config/db")

//首页的接口

//轮播图接口
router.get("/banner", async (req, res, next) => {
    let sql = `SELECT * FROM e_banners WHERE isshow=1`;
    let result = await query(sql);
    res.send({
        success: true,
        msg: "查询成功",
        status: 200,
        data: result
    })
})

//课程列表 /course?type=1
router.get("/course", async (req, res, next) => {
    let sql = `SELECT * FROM e_course WHERE type='${req.query.type}'`;
    let result = await query(sql);
    res.send({
        success: true,
        msg: "查询成功",
        status: 200,
        data: result
    })
})


//注册的接口 
// 请求参数：用户名（username） 密码(password) 创建时间(createdate)
// 响应：注册的结果
router.post("/register", async (req, res, next) => {
    //取参数
    let { username, password, createdate } = req.body;

    //验证之前是否已经注册过
    let sql2=`select * from e_member where username='${username}'`;
    let result2=await query(sql2);

    if(result2.length>0){//有这个用户
        next("该用户已注册")
        return;
    }

    // 密码加密
    password= md5(md5(password).substr(5,6))

    //注册
    let mid=new Date().getTime()+(Math.random()+'').substr(2,6)
    let sql1=`insert into e_member (mid,username,password,sex,createdate) values ('${mid}','${username}','${password}','1','${createdate}')`
    let result1=await query(sql1);
    if(result1.affectedRows>0){
        res.send({
            success:true,
            msg:"注册成功",
            status:200
        })
    }else{
        next("注册失败")
    }
})


// 登录 [作业]

module.exports = router;
